﻿@model IEnumerable<string>
@{
    ViewBag.Title = "Leffaetsin - Nautintoasi ajatellen";
}
<div data-role="header">
    <h1>@ViewBag.Title</h1>
</div>

<div data-role="content">

    <div>
        <h3>Mikä leffaetsin?</h3>
        <p>Leffaetsin hakee Suomen elokuvateattereissa tänään näytettävät elokuvat, hakee niille arviot IMDB:stä ja listaa parhaiten arvioidut leffat ensin.</p>
        <p>Ole hyvä.</p>
    </div>

    <h3>Valitse kaupunki</h3>

    <ul data-role="listview">
        <li>
            <a onClick="getLocationFunction()"><h3>Etsi kaupunki automaattisesti</h3></a>
        </li>
        @foreach(var area in Model) {
            <li>
                <a href="@Url.Action("Movies", new { area = area })">
                    <h3>@area</h3>
                </a>
            </li>                                           
        }    
    </ul>

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript">


    //The function acts as a callback method for the button  widget presented to the user
    function getLocationFunction() {
        //check if user accepts to share geolocation
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(cityCalculatorFunction, errorFunction);

        } else {
            alert("Your Browser is outdated and does not support this feature.\nUpdate your Browser to the latest version or choose the city from the main menu.");
        }
    }
    //The function is called if an error occurs in getLocationFunction()
    function errorFunction() {
        alert("City GeoLocator failed");
    }


    //The function finds the user's city based on latitude and longitude
    function cityCalculatorFunction(position) {
        var geocoder = new google.maps.Geocoder();
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
        var latlng = new google.maps.LatLng(lat, lng);
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                //The results array contains a 'city,country' string at position 4, array is 0 based
                if (results[3]) {
                    var cityAndCountry = results[3].formatted_address;
                    var city = cityAndCountry.split(", ")[0];
                    //redirect to leffaetsin
                    window.location.replace("/" + city);
                } else {
                    alert("The system was unable to find your location automatically. Choose your city from the main menu.");
                }

            } else {
                alert("Geocoder failed due to: " + status);
            }
        });
    }
</script> 

</div>